import { createRouter, createWebHistory } from 'vue-router';
import Login from '../views/Login.vue';
import AdminLayout from '../views/AdminLayout.vue';
import Dashboard from '../views/Dashboard.vue';
import UserManagement from '../views/UserManagement.vue';
import DeviceManagement from '../views/DeviceManagement.vue';
import Profile from '../views/Profile.vue';

const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        name: 'Login',
        component: Login
    },
    {
        path: '/admin',
        name: 'Admin',
        component: AdminLayout,
        redirect: '/admin/dashboard',
        children: [
            {
                path: 'dashboard',
                name: 'Dashboard',
                component: Dashboard
            },
            {
                path: 'users',
                name: 'UserManagement',
                component: UserManagement
            },
            {
                path: 'devices',
                name: 'DeviceManagement',
                component: DeviceManagement
            },
            {
                path: 'profile',
                name: 'Profile',
                component: Profile
            }
        ]
    }
];

const router = createRouter({
    history: createWebHistory(),
    routes
});

// 添加路由守卫
router.beforeEach((to, from, next) => {
    const isLoggedIn = localStorage.getItem('userInfo');

    if (to.path.startsWith('/admin') && !isLoggedIn) {
        next('/login');
    } else {
        next();
    }
});

export default router;